import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp

from models.Messages import *
from models.Topics import *
from models.Groups import *
from models.Users import *
from models.Audit import *
from models.Authentication import *
from decorators import *
import logging


"""------------------------------------------------------------------------
ViewGroups
------------------------------------------------------------------------"""
# @CheckUserCreated
class ViewGroups(webapp.RequestHandler):
    def get(self):        
        
        ourUser = get_current_user(request=self.request)
        logging.info(ourUser)
        
        if not ourUser:
          return self.redirect("/login")
        
        welcome = False
        moderator = ourUser.moderator
        super_user = ourUser.super_user
        
        if(ourUser.firstTime):
            welcome = True
            ourUser.firstTime = False
            ourUser.put()
        
        # fetch the groups that our users are a member of
        if len(ourUser.groups) > 0:
          logging.info(ourUser.groups)
          groups = Group.get_by_id(ourUser.groups)
          #groups.filter('key.id IN ', ourUser.groups)
        else:
          groups = []
        
        logging.info(groups)
        groupsWithCount = []
        for group in groups:
            if group == None:
              continue
            topics = Topic.all()
            topics.filter("group_id =",group.key().id())
            count = topics.count()
            groupsWithCount.append({"group":group,"count":count})

        template_values = {"groups":groupsWithCount,"welcome":welcome,"user":ourUser, "moderator":moderator, "super_user":super_user}
        
        # getting the user agent style of the user
        user_agent = self.request.headers["User-Agent"]
        
        # redirect the user to the mobile template instead of 
        # regular template
        if user_agent.find("Mobile") >= 0:
          logging.info("You should redirect to the mobile site")
          path = os.path.join(os.path.dirname(__file__), "../templates/mobileMaster.html")
          self.response.out.write(template.render(path, template_values))
        # If we are in the standard browser then just render the normal one.
        else:
          path= os.path.join(os.path.dirname(__file__), "../templates/ViewGroups.html")
          self.response.out.write(template.render(path, template_values))

"""------------------------------------------------------------------------
NewGroup
------------------------------------------------------------------------"""
class NewGroup(webapp.RequestHandler):
    def get(self):
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        if not ourUser.super_user:
          return self.redirect("/group")
        path = os.path.join(os.path.dirname(__file__),"../templates/NewGroup.html")
        self.response.out.write(template.render(path,{}))

    def post(self):
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        #fetch the current user who will be the author
        
        currUser = get_current_user(self.request)

        requestTitle = self.request.get('title')
        member_list = self.request.get("member_list")
        newGroup = Group(title=requestTitle)
                
        # add the author to the moderators list.
        newGroup.moderators.append(currUser.email)

        newGroup.author = currUser.key().id()
        newGroup.put()
        
        # add the newly created group to the current users groups list
        currUser.groups.append(int(newGroup.key().id()))
        logging.info(newGroup.key().id())
        logging.info(currUser.groups)
        currUser.put()

        audit = Audit(
            ip = self.request.remote_addr,
            action = "New Group",
            date = newGroup.date_created,
            userID = currUser.key().id(),
            objectID = newGroup.key().id() 
        )
        audit.setGroup()
        audit.put()
        
        self.redirect('/group/'+ str(newGroup.key().id()))



"""------------------------------------------------------------------------
DeleteGroup
------------------------------------------------------------------------"""
class DeleteGroup(webapp.RequestHandler):
    def get(self,groupID):
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        group = Group.get_by_id(int(groupID))
        
        currUser = get_current_user(self.request)
        
        audit = Audit(
            ip = self.request.remote_addr,
            action = "Delete Group",
            date = group.date_created,
            userID = currUser.key().id(),
            objectID = group.key().id() 
        )
        audit.setGroup()
        audit.put()
        logging.info(currUser.groups)
        logging.info(groupID)
        currUser.groups.remove(long(groupID))
        group.delete()
        # currUser.groups.remove(None)
        logging.info(currUser.groups)
        self.redirect('/group')
        

"""------------------------------------------------------------------------
ModifyGroup
------------------------------------------------------------------------"""
class ModifyGroup(webapp.RequestHandler):
    def get(self,groupID):
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        group = Group.get_by_id(int(groupID))

        template_values = {"group":group}
        path = os.path.join(os.path.dirname(__file__),"../templates/ModifyGroup.html")
        self.response.out.write(template.render(path,template_values))
    def post(self,groupID):
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        group = Group.get_by_id(int(groupID))

        query = D5User.all()
        query.filter("google_user = ",users.get_current_user())
        currUser = query.get()
        audit = Audit(
            ip = self.request.remote_addr,
            action = "Modify Group (Changed name to: "+self.request.get('groupTitle')+ ")",
            date = group.date_created,
            userID = currUser.key().id(),
            objectID = group.key().id() 
        )
        
        audit.setGroup()
        audit.put()


        group.title = self.request.get('groupTitle')
        group.put()
        self.redirect('/group/'+str(group.key().id()))
